<script lang="ts">
  import { Button } from "$lib/components/ui/button";
  import { reports, reportActions } from "$lib/store";
  import type { DailyReport } from "$lib/types";
  import { Copy, Trash2, Check, Square } from "lucide-svelte";

  async function handleDelete(id: string, reportDate: string) {
    const confirmMessage = `确定要删除 "${reportDate}" 的日报吗？\n\n此操作不可恢复！`;
    if (confirm(confirmMessage)) {
      const success = await reportActions.deleteReport(id);
      if (success) {
        alert('删除成功！');
      } else {
        alert('删除失败，请重试');
      }
    }
  }

  async function handleCopy(report: DailyReport) {
    const success = await reportActions.copyReport(report);
    if (success) {
      alert('日报内容已复制到剪切板！');
    } else {
      alert('复制失败，请重试');
    }
  }

  // 格式化显示完整的日报内容
  function formatReportContent(report: DailyReport): string {
    let content = `${report.date} 工作日报\n\n`;
    
    if (report.todayWork?.trim()) {
      content += `一、今日工作汇报\n${report.todayWork}\n\n`;
    }
    
    if (report.tomorrowPlan?.trim()) {
      content += `二、明日工作计划\n${report.tomorrowPlan}\n\n`;
    }
    
    if (report.weekPlan?.trim()) {
      content += `三、下周工作计划\n${report.weekPlan}`;
    }
    
    return content.trim();
  }

  // 批量删除相关状态
  let selectedReports = $state<Set<string>>(new Set());
  let showBatchActions = $state(false);

  function toggleReportSelection(reportId: string) {
    if (selectedReports.has(reportId)) {
      selectedReports.delete(reportId);
    } else {
      selectedReports.add(reportId);
    }
    selectedReports = new Set(selectedReports);
    showBatchActions = selectedReports.size > 0;
  }

  function selectAllReports() {
    if (selectedReports.size === $reports.length) {
      selectedReports.clear();
    } else {
      selectedReports = new Set($reports.map(r => r.id));
    }
    selectedReports = new Set(selectedReports);
    showBatchActions = selectedReports.size > 0;
  }

  async function handleBatchDelete() {
    const count = selectedReports.size;
    if (confirm(`确定要删除选中的 ${count} 条日报吗？\n\n此操作不可恢复！`)) {
      let successCount = 0;
      for (const reportId of selectedReports) {
        const success = await reportActions.deleteReport(reportId);
        if (success) successCount++;
      }
      
      selectedReports.clear();
      selectedReports = new Set();
      showBatchActions = false;
      
      if (successCount === count) {
        alert(`成功删除 ${successCount} 条日报！`);
      } else {
        alert(`删除完成：成功 ${successCount} 条，失败 ${count - successCount} 条`);
      }
    }
  }
</script>

<div class="space-y-6 font-notion">
  <!-- 标题栏 -->
  <div class="flex items-center justify-between">
    <div class="flex items-center gap-4">
      <h2 class="text-2xl font-bold text-notion-text">📋 日报列表</h2>
      {#if $reports.length > 0}
        <button
          onclick={selectAllReports}
          class="flex items-center gap-2 px-3 py-1 text-sm text-notion-text-secondary hover:text-notion-text transition-colors"
        >
          {#if selectedReports.size === $reports.length}
            <Check class="w-4 h-4" />
            取消全选
          {:else}
            <Square class="w-4 h-4" />
            全选
          {/if}
        </button>
      {/if}
    </div>
    
    <div class="flex items-center gap-3">
      {#if showBatchActions}
        <div class="flex items-center gap-2">
          <span class="text-sm text-notion-text-light">已选择 {selectedReports.size} 条</span>
          <Button
            onclick={handleBatchDelete}
            variant="outline"
            size="sm"
            class="border-red-300 text-red-600 hover:bg-red-50 rounded-notion flex items-center gap-1"
          >
            <Trash2 class="w-3 h-3" />
            批量删除
          </Button>
        </div>
      {/if}
      <div class="text-sm text-notion-text-light bg-notion-bg-secondary px-3 py-1 rounded-notion">
        共 {$reports.length} 条记录
      </div>
    </div>
  </div>

  {#if $reports.length === 0}
    <div class="text-center py-16 bg-notion-bg rounded-notion-lg shadow-notion border border-notion-border">
      <div class="text-8xl mb-6 opacity-50">📝</div>
      <h3 class="text-xl font-semibold text-notion-text mb-2">暂无日报记录</h3>
      <p class="text-notion-text-light">开始编写你的第一份日报吧！</p>
    </div>
  {:else}
    <div class="space-y-4">
      {#each $reports.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()) as report (report.id)}
        <div class="bg-notion-bg border border-notion-border rounded-notion-lg shadow-notion hover:shadow-notion-hover transition-all duration-200 group {selectedReports.has(report.id) ? 'ring-2 ring-notion-accent ring-opacity-50' : ''}">
          <!-- 标题栏 -->
          <div class="p-6 border-b border-notion-border-light">
            <div class="flex items-start justify-between">
              <div class="flex items-center gap-3 flex-1">
                <button
                  onclick={() => toggleReportSelection(report.id)}
                  class="text-notion-text-secondary hover:text-notion-text transition-colors"
                >
                  {#if selectedReports.has(report.id)}
                    <Check class="w-4 h-4 text-notion-accent" />
                  {:else}
                    <Square class="w-4 h-4" />
                  {/if}
                </button>
                <div class="flex-1">
                  <h3 class="text-lg font-semibold text-notion-text mb-1 group-hover:text-notion-accent transition-colors">
                    {report.date} 工作日报
                  </h3>
                </div>
              </div>
              
              <!-- 操作按钮 -->
              <div class="flex gap-2 ml-4 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                <Button 
                  variant="outline" 
                  size="sm" 
                  onclick={() => handleCopy(report)}
                  class="border-notion-border text-notion-accent hover:bg-notion-accent-light rounded-notion transition-all duration-200 flex items-center gap-1"
                >
                  <Copy class="w-3 h-3" />
                  复制
                </Button>
                <Button 
                  variant="outline" 
                  size="sm" 
                  onclick={() => handleDelete(report.id, report.date)}
                  class="border-red-300 text-red-600 hover:bg-red-50 rounded-notion transition-all duration-200 flex items-center gap-1"
                >
                  <Trash2 class="w-3 h-3" />
                  删除
                </Button>
              </div>
            </div>
          </div>
          
          <!-- 完整日报内容预览 -->
          <div class="p-6">
            <div class="bg-white border border-notion-border rounded-lg p-6">
              <pre class="text-notion-text leading-7 whitespace-pre-wrap text-sm font-mono">{formatReportContent(report)}</pre>
            </div>
            
            <!-- 底部时间信息 -->
            <div class="flex justify-between items-center mt-4 pt-4 border-t border-notion-border-light text-xs text-notion-text-lighter">
              <span>创建：{new Date(report.createdAt).toLocaleString('zh-CN')}</span>
              {#if report.updatedAt !== report.createdAt}
                <span>更新：{new Date(report.updatedAt).toLocaleString('zh-CN')}</span>
              {/if}
            </div>
          </div>
        </div>
      {/each}
    </div>
  {/if}
</div>